<template>
  <el-card shadow="never">
    <el-row>👏欢迎回来</el-row>
    <el-divider></el-divider>
    <el-row>
      <el-col :span="8">
        <div style="display: flex; align-items: center; gap: 12px">
          <el-avatar :src="count_img"></el-avatar>
          <div>
            <p class="content-count">总用户数</p>
            <countTo :endVal="user_count"></countTo>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div style="display: flex; align-items: center; gap: 12px">
          <el-avatar :src="total_img"></el-avatar>

          <div>
            <p class="content-count">总访问量</p>
            <countTo :endVal="visit_count"></countTo>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div style="display: flex; align-items: center; gap: 12px">
          <el-avatar :src="increase_img"></el-avatar>
          <div>
            <p class="content-count">{{ user_increase.text }}</p>
            <countTo :endVal="user_increase.value"></countTo>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-divider></el-divider>

    <div style="justify-content: space-between; display: flex; margin-top: 40px">
      <div style="position: relative; width: 50%; height: 400px">
        <div ref="contentEchart" style="width: 100%; height: 100%"></div>
        <el-button
          @click="getContentData"
          type="text"
          style="position: absolute; right: 6%; top: 0; padding: 4px"
          >查看更多</el-button
        >
      </div>
      <div ref="clickEchart" style="width: 40%; height: 400px"></div>
    </div>
    <el-row>
      <i class="el-icon-message-solid" style="color: red"></i>
      <span style="margin: 0 24px 0 8px">今日预警</span>
      <el-tooltip
        class="item"
        effect="dark"
        placement="top"
      >
        <template v-slot:content>
          <div v-html="renderErrorContent(error_content)"></div>
        </template>
        <span
          style="
            padding: 8px;
            background-color: red;
            color: aliceblue;
            font-size: 12px;
            font-weight: 800;
            box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.2);
          "
          >{{ warning_user }}人</span
        >
      </el-tooltip>
    </el-row>
  </el-card>
</template>

<script>
//数字滚动计时
import countTo from 'vue-count-to';
export default {
  name: '',
  data() {
    return {
      day: 0,
      warning_user: 0,
      count_img: require('@/assets/images/count.png'),
      increase_img: require('@/assets/images/increase.png'),
      total_img: require('@/assets/images/total.png'),
      user_count: 0,
      visit_count: 0,
      user_increase: {
        value: 0,
        text: '用户增长数量',
      },
      contentOption: {
        title: [
          {
            text: '内容数据 (近7天)',
            left: 'left',
            top: 'top',
            textStyle: {
              fontWeight: 'bold',
            },
          },
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        grid: {
          top: '15%',
          bottom: '10%',
          left: '10%',
          right: '10%',
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: [],
            name: '访问量',
            showSymbol: false,
            type: 'line',
            smooth: true,
            lineStyle: {
              width: 2, // 线条宽度
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                // 渐变方向从左到右
                {
                  offset: 0,
                  color: '#43eaff', // 起始颜色
                },
                {
                  offset: 1,
                  color: '#7347fb', // 结束颜色，注意去掉了透明度的设置，因为通常线条不需要透明渐变
                },
              ]),
            },
            areaStyle: {
              opacity: 1,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: '#dfeeff',
                },
                {
                  offset: 0.5,
                  color: '#f4f9ff',
                },
                {
                  offset: 1,
                  color: '#ffffff',
                },
              ]),
            },
          },
        ],
      },
      clickOption: {
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            return (
              `${params.name} : ${params.percent}%` + '<br/>' + `点击量：${params.data.click_count}`
            );
          },
        },
        legend: {
          bottom: '5%',
          left: 'center',
        },
        title: [
          {
            text: '模块点击量占比',
            left: 'left',
            top: 'top',
            textStyle: {
              // 加粗
              fontWeight: 'bold',
            },
          },
        ],
        series: [
          {
            label: {
              // alignTo: 'edge',
              formatter: '{name|{b}}\n{time|{c} %}',
              minMargin: 5,
              edgeDistance: 10,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: '#999',
                },
              },
            },
            name: '模块占比',
            type: 'pie',
            radius: ['40%', '60%'],
            data: [],
            formatter: '{d}',
          },
        ],
      },
      error_content: '无预警人数',
    };
  },
  components: {
    countTo,
  },
  methods: {
    getLineData() {
      this.content_echart = echarts.init(this.$refs.contentEchart);
      this.click_echart = echarts.init(this.$refs.clickEchart);
      this.click_echart.setOption(this.clickOption);
      this.content_echart.setOption(this.contentOption);
    },
    async getUserCount() {
      const { data } = await this.$http.get('/api/monitor/user_count');
      this.user_count = data;
    },
    async getUserVisitCount() {
      const { data } = await this.$http.get('/api/monitor/visit_count');
      this.visit_count = data;
    },
    async getUserIncrease() {
      const { data, msg } = await this.$http.get('/api/monitor/user_increase');
      this.user_increase.value = data.length;
      this.user_increase.text = msg;
    },
    async getContentData() {
      this.day += 7;
      const { data, msg, code } = await this.$http({
        method: 'get',
        url: '/api/monitor/visit_count_days',
        params: {
          day: this.day,
        },
      });
      if (code) return this.$message.error(msg);
      if (data === 0) return;
      this.contentOption.series[0].data = data;
      this.contentOption.title[0].text = `内容数据 (近${this.day}天)`;
      // 更新echart
      this.content_echart?.setOption(this.contentOption);
    },
    async getModuleClickData() {
      const { data, msg, code } = await this.$http.get('/api/monitor/module_click');
      if (code) return this.$message.error(msg);
      if (data === 0) return;
      // 计算总量
      let total = data.reduce((arr, cur) => {
        return arr + cur.value;
      }, 0);
      // 转成百分比
      this.clickOption.series[0].data = data.map((item) => {
        return {
          name: item.name,
          value: Math.round((item.value / total) * 100),
          click_count: item.value,
        };
      });
      this.click_echart?.setOption(this.clickOption);
    },
    async getWarningUser() {
      const { data, msg, code } = await this.$http.get('/api/monitor/warning_user');
      if (code) return this.$message.error(msg);
      this.warning_user = data;
      let error_content = msg.replaceAll('-', '\t').replaceAll(',', '\n');
      this.error_content = error_content + '';
    },
    renderErrorContent(text) {
      return `<pre>${text}</pre>`;
    },
  },
  async mounted() {
    // 获取用户数据
    await this.getContentData();
    // 获取模块点击量
    await this.getModuleClickData();
    // 获取预警人数
    await this.getWarningUser();
    // 渲染图
    this.getLineData();

    window.addEventListener('resize', () => {
      this.content_echart.resize();
      this.click_echart.resize();
    });
  },
  async created() {
    await this.getUserIncrease();
    await this.getUserCount();
    await this.getUserVisitCount();
  },
  watch: {},
  computed: {},
  filters: {},
};
</script>

<style scoped lang="less">
.content-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: aqua;
}

.content-count {
  font-size: 12px;
  margin-bottom: 12px;
}

.lfCard {
  transition: all 0.2s linear;
  cursor: pointer;

  &:hover {
    transform: translate3d(0, -5px, 0);
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
  }

  .pic {
    width: 120px;
    height: 120px;
  }

  .info {
    span {
      font-size: 12px;
    }
  }
}

.card {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;

  .el-card {
    width: 22%;
    height: 100px;
    color: #fff;
    transition: all 0.3s linear;
    cursor: pointer;

    &:hover {
      transform: translate3d(0, -5px, 0);
      box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);

      .jumpNum {
        text-shadow: 0 0 10px #fff;
      }
    }

    p {
      font-size: 12px;
    }
  }

  .orderCard {
    width: 97%;
    margin: 20px 0;
    height: 144px;

    &:hover {
      cursor: pointer;
    }

    .el-descriptions {
      /deep/.el-descriptions__header {
        margin-bottom: 5px;
      }

      /deep/.el-descriptions-item {
        font-size: 12px;
        padding: 10px 40px;

        .el-descriptions-item__container {
          border-bottom: 1px solid #eee;
          padding-bottom: 5px;
          width: 180px;
        }

        .el-descriptions-item__content {
          margin-left: 85px;
          color: #ff7675;
        }
      }
    }
  }
}
</style>
